
/*
 * @Author: silence
 * @Date: 2022-05-28 15:53:42
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-07-27 15:52:18
 * @Description: 为了避免用户误触返回按钮而导致 App 退出
 */
import 'package:ems_neutral_app/pages/Mine/Language/LanguageController.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';

class WillPopScopeAppPage extends StatefulWidget {
  final Widget child;
  const WillPopScopeAppPage({required this.child, super.key});

  @override
  State<WillPopScopeAppPage> createState() => _WillPopScopeAppPageState();
}

class _WillPopScopeAppPageState extends State<WillPopScopeAppPage> {
  /// 上次退出的时间
  DateTime? lastPopTime;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: AbsorbPointer(
            absorbing: false, // Platform.isIOS ? click : false,
            child: widget.child),
        onWillPop: () async {
          // 点击返回键的操作
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime ?? DateTime.now()) >
                  Duration(seconds: 2)) {
            lastPopTime = DateTime.now();
            LanguageController languageController = LanguageController();
            String prompt = languageController.isPromptEnglish() ? "Press back to the desktop again" : "再按一次退回桌面";
            SilToast.show(prompt);
            return false;
          } else {
            lastPopTime = DateTime.now();
            // 退出app
            await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            return true;
          }
        });
  }
}
